package com.itlong.cloud.controller.sdkV2.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.AppCallLiftSaveDTO;
import com.itlong.cloud.POJO.DTO.common.PadFaceSyncDataDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateDeveloperAuthDeviceAuthListDTO;
import com.itlong.cloud.POJO.DTO.property.*;
import com.itlong.cloud.POJO.DTO.sdk.*;
import com.itlong.cloud.POJO.DTO.sdk.sendPush.SendPushMessageDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.SDKMessageVO;
import com.itlong.cloud.POJO.VO.app.AppCreateBaiduFaceVO;
import com.itlong.cloud.POJO.VO.app.robot.AppProjectRobotInfoVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeveloperAuthDeviceAuthVO;
import com.itlong.cloud.POJO.VO.operate.OperateFaceApplyInfoVO;
import com.itlong.cloud.POJO.VO.sdk.SDKServerProjectInfoListPageVO;
import com.itlong.cloud.POJO.VO.sdk.SDKServerProjectInfoListVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.controller.sdkV2.elevator.SDKCloudElevatorCTLController;
import com.itlong.cloud.controller.sdkV2.elevator.SDKCloudElevatorRTLController;
import com.itlong.cloud.controller.sdkV2.elevator.SDKCloudRobotNoninductiveController;
import com.itlong.cloud.controller.sdkV2.entrance.SDKCloudEntranceController;
import com.itlong.cloud.controller.sdkV2.face.SDKFaceRecognitionController;
import com.itlong.cloud.controller.sdkV2.intercom.app.SDKCloudTalkAppController;
import com.itlong.cloud.controller.sdkV2.intercom.server.SDKCloudTalkEquipController;
import com.itlong.cloud.controller.sdkV2.intercom.server.SDKCloudTalkMediaController;
import com.itlong.cloud.controller.sdkV2.intercom.server.SDKCloudTalkProjectController;
import com.itlong.cloud.controller.sdkV2.intercom.server.SDKCloudTalkUserController;
import com.itlong.cloud.controller.sdkV2.qrcode.SDKQrCodeController;
import com.itlong.cloud.controller.sdkV2.serverClient.SDKOfflineProjectController;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.enumerate.ecode.*;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.commons.ICloudEntranceServiceClient;
import com.itlong.cloud.equip.property.IPropertyDeviceAuthServiceClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKRobotClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKServerCloudServiceClient;
import com.itlong.cloud.iottp.IIotBaiduFaceServiceClient;
import com.itlong.cloud.project.operate.IOperateFaceApplyServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.project.sdk.ICloudTalkSDKServerProjectServiceClient;
import com.itlong.cloud.project.sdk.ISDKServerProjectServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import com.itlong.cloud.user.operate.IOperateDeveloperAuthServiceClient;
import com.itlong.cloud.user.operate.IOperatePropertyAccountServiceClient;
import com.itlong.cloud.user.operate.IOperateUserInfoServiceClient;
import com.itlong.cloud.user.property.IPropertyHouseHoldInfoServiceClient;
import com.itlong.cloud.user.property.IPropertyHouseholdRoleServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKAppUserServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.user.sdk.IFaceSDKVisitorServiceClient;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.encrypt.Md5;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.file.ImgageUtil;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 * 云设备SDK 共同方法
 * </desc>
 *
 * @createDate 2019/08/27
 */
@RestController
@RequestMapping("/sdk/cloud/base")
public class SDKCloudBaseController {


    private static final Logger LOG = LoggerFactory.getLogger(SDKCloudBaseController.class);

    @Autowired
    SDKCloudElevatorCTLController sdkCloudElevatorCTLController;

    @Autowired
    SDKCloudElevatorRTLController sdkCloudElevatorRTLController;

    @Autowired
    SDKCloudEntranceController sdkCloudEntranceController;

    @Autowired
    SDKCloudRobotNoninductiveController sdkCloudRobotNoninductiveController;

    @Autowired
    ICloudElevatorSDKRobotClient iCloudElevatorSDKRobotServiceClient;

    @Autowired
    private ICloudElevatorSDKServerCloudServiceClient iCloudElevatorSDKServerCloudServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    ICloudEntranceServiceClient iCloudEntranceServiceClient;

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    IOperatePropertyAccountServiceClient iOperatePropertyAccountServiceClient;

    @Autowired
    ISDKServerOldUserServiceClient iSDKServerUserServiceClient;

    @Autowired
    IAppHomeServiceClient iAppHomeServiceClient;

    @Autowired
    RedisService redisService;

    @Autowired
    ISDKServerOldUserServiceClient iSDKUserServiceClient;

    @Autowired
    ICloudTalkSDKAppUserServiceClient iCloudTalkSDKAppUserServiceClient;

    @Autowired
    ICloudTalkSDKServerProjectServiceClient iCloudTalkSDKServerProjectServiceClient;

    @Autowired
    SDKQrCodeController sdkQrCodeController;

    @Autowired
    SDKCloudTalkUserController sdkCloudTalkUserController;

    @Autowired
    SDKOfflineProjectController sdkServerProjectController;

    @Autowired
    SDKCloudTalkEquipController sdkCloudTalkEquipController;

    @Autowired
    SDKCloudTalkProjectController sdkCloudTalkProjectController;

    @Autowired
    SDKCloudTalkAppController sdkCloudTalkAppController;

    @Autowired
    IOperateDeveloperAuthServiceClient iOperateDeveloperAuthServiceClient;

    @Autowired
    SDKFaceRecognitionController sdkFaceRecognitionController;

    @Autowired
    SDKCloudTalkMediaController sdkCloudTalkMediaController;

    @Autowired
    IFaceSDKVisitorServiceClient iFaceSDKVisitorServiceClient;

    @Autowired
    IOperateUserInfoServiceClient iOperateUserInfoServiceClient;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    ISDKServerProjectServiceClient isdkServerProjectServiceClient;

    @Autowired
    IPropertyHouseHoldInfoServiceClient iPropertyHouseHoldInfoServiceClient;

    @Autowired
    IPropertyHouseholdRoleServiceClient iPropertyHouseholdRoleServiceClient;

    @Autowired
    IPropertyDeviceAuthServiceClient iPropertyDeviceAuthServiceClient;

    @Autowired
    IOperateFaceApplyServiceClient iOperateFaceApplyServiceClient;

    @Autowired
    IIotBaiduFaceServiceClient iIotBaiduFaceServiceClient;


    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    private String APP_USER_TOKEN_KEY;

    @Value("${" + PlatformConstants.ROBOTGO_APP_SECRET + "}")
    private String APP_SECRET;

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;
    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;
    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;
    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;
    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    /**
     * <desc>
     * SDK开发者认证
     * <desc/>
     *
     * @param encryptScript 加密入参
     * @param appId 开发者账号
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/09/16
     */
    @ResponseBody
    @PostMapping("/developerLogin")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_DEVELOPER_LOGIN_LOG_DESC)
    @UnAuthAccessRequired
    public Object developerLogin(String encryptScript,String appId) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String responseTimestamp = new Date().getTime()+"";
        try {
            if (StringUtils.isBlank(appId) || StringUtils.isBlank(encryptScript)) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),"",responseTimestamp,"");//此时没有加密签名直接明文返回报错信息
            }
            request.setAttribute("appId", appId);

            PropertyUserInfoPO propertyUserInfoPO = iSDKUserServiceClient.getPropertyUserByAppId(appId);
            //无此开发者信息时或开发者密码不正确时
            if (propertyUserInfoPO == null || StringUtils.isBlank(propertyUserInfoPO.getAppsecret())) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_PARAM_APPID_APPSECRET_ERR.getErrorCode(),"",responseTimestamp,"");//此时没有加密签名直接明文返回报错信息
            }
            if (propertyUserInfoPO.getStatus() != 1) {
                return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVELOPER_STATUS_ERR.getErrorCode(),"",responseTimestamp,""), propertyUserInfoPO.getAppsecret());
            }

            CloudDeviceSDKDTO dto = new CloudDeviceSDKDTO();
            String encryptResult = DesEncryptUtil.aesDecrypt(encryptScript, propertyUserInfoPO.getAppsecret());
            if (StringUtils.isBlank(encryptResult)) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_PARAM_APPID_APPSECRET_ERR.getErrorCode(),"",responseTimestamp,"");//此时没有加密签名直接明文返回报错信息
            }
            Map<String, Object> params;
            JSONObject jsStr = JSONObject.parseObject(encryptResult);//入参转json
            String requestId;
            try {
                requestId = jsStr.get("requestId") == null ? "" : jsStr.get("requestId").toString();
                String timestamp = jsStr.get("timestamp") == null ? "" : jsStr.get("timestamp").toString();
                request.setAttribute("requestId", requestId);
                request.setAttribute("timestamp", timestamp);
                JSONObject protocol = JSONObject.parseObject(jsStr.get("protocol").toString());
                request.setAttribute("version", protocol.get("version") == null ? "" : protocol.get("version").toString());
                JSONObject client = JSONObject.parseObject(jsStr.get("client").toString());
                JSONObject param = JSONObject.parseObject(jsStr.get("param").toString());
                params = JsonUtil.toObject(protocol.toString(), HashMap.class);
                params.putAll(JsonUtil.toObject(client.toString(), HashMap.class));
                params.putAll(JsonUtil.toObject(param.toString(), HashMap.class));

                //保存生成操作日志所需信息 详细描述和接口类别
                request.setAttribute("remark", "appId:"+appId + "|" + "appSecret:"+params.get("appSecret") + "robotId:"+param.get("robotId"));
                request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
                dto.setAppId(appId);
                dto.setAppSecret(params.get("appSecret").toString());
                params.remove("appSecret");

                //验签
                String sign = jsStr.get("sign").toString();
                if (!Md5EncryptUtil.checkSDKV2Sign(params, sign, requestId, timestamp, propertyUserInfoPO.getAppsecret())) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_MD5_ERROR.getErrorCode(),requestId,responseTimestamp,""), propertyUserInfoPO.getAppsecret());
                }
            }catch (Exception e){
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_INPUT_PARAM_ERR.getErrorCode(),"",responseTimestamp,"");//json格式解析失败
            }

            String token = iCloudTalkSDKAppUserServiceClient.developerLogin(propertyUserInfoPO,params.get("robotId")== null?null:params.get("robotId").toString());
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            request.setAttribute("token", token);

            Map<String, Object> signMap = new HashMap<>();
            signMap.put("data",new JSONObject(map));//签名使用json格式内容进行

            return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), requestId, responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(signMap,requestId,responseTimestamp, propertyUserInfoPO.getAppsecret()), map), propertyUserInfoPO.getAppsecret());
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_developerLogin】SDK开发者认证", e);
        }
    }

    /**
     * <desc>
     * 获取设备唯一标识
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/09/16
     */
    @ResponseBody
    @PostMapping("/getDeviceKey")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_CLOUD_DEVICE_UNIQUE_LOG_DESC)
    public Object getDeviceKey() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            dto.setAppId(request.getAttribute("appId").toString());
            dto.setAppSecret(request.getAttribute("appSecret").toString());
            String responseTimestamp = new Date().getTime()+"";
            dto.setResponseTimestamp(responseTimestamp);
            LOG.info("======getDeviceKey获取设备唯一标识============入参================>{}",null==dto?"":dto.toString());

            if (StringUtils.isBlank(dto.getDeviceType()) || StringUtils.isBlank(dto.getProjectId())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            switch (dto.getDeviceType()) {
                //云电梯机器人对云端
                case "1":
                    dto.setRobotDevelopDeviceType(2);
                    return sdkCloudElevatorRTLController.getElevatorKey(dto);
                //云电梯云端对云端
                case "2":
                    return sdkCloudElevatorCTLController.getElevatorKey(dto);
                //云门禁
                case "3":
                    return sdkCloudEntranceController.getEntranceKey(dto);
                //机器人无感
                case "4":
                    dto.setRobotDevelopDeviceType(1);
                    return sdkCloudElevatorRTLController.getElevatorKey(dto);
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),responseTimestamp, dto.getAppSecret()), null);
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getDeviceKey】获取设备唯一标识异常", e);
        }
    }

    /**
     * <desc>
     * 获取设备信息
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/09/17
     */
    @ResponseBody
    @PostMapping("/getDeviceInfo")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_CLOUD_INFO_LOG_DESC)
    public Object getDeviceInfo() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            dto.setAppId(request.getAttribute("appId").toString());
            dto.setAppSecret(request.getAttribute("appSecret").toString());
            String responseTimestamp = new Date().getTime()+"";
            dto.setResponseTimestamp(responseTimestamp);
            LOG.info("======getDeviceInfo获取设备信息============入参================>{}",null==dto?"":dto.toString());

            if (StringUtils.isBlank(dto.getDeviceType()) || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getDeviceUnique())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            switch (dto.getDeviceType()) {
                //云电梯机器人对云端
                case "1":
                    dto.setRobotDevelopDeviceType(2);
                    return sdkCloudElevatorRTLController.getElevatorInfo(dto);
                //云电梯云端对云端
                case "2":
                    return sdkCloudElevatorCTLController.getElevatorInfo(dto);
                //云门禁
                case "3":
                    return sdkCloudEntranceController.getEntranceInfo(dto);
                //机器人无感通行
                case "4":
                    dto.setRobotDevelopDeviceType(1);
                    return sdkCloudRobotNoninductiveController.getElevatorInfo(dto);
                //云对讲
                case "5":
                    return sdkCloudTalkEquipController.getCloudTalkDeviceList(dto);
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),responseTimestamp, dto.getAppSecret()), null);
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getDeviceInfo】获取设备信息异常", e);
        }
    }

    /**
     * <desc>
     * 获取设备状态
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/09/17
     */
    @ResponseBody
    @PostMapping("/getDeviceStatus")
    public Object gerDeviceStatus() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            dto.setAppId(request.getAttribute("appId").toString());
            dto.setAppSecret(request.getAttribute("appSecret").toString());
            String responseTimestamp = new Date().getTime()+"";
            dto.setResponseTimestamp(responseTimestamp);
            LOG.info("======gerDeviceStatus获取设备状态============入参================>{}",null==dto?"":dto.toString());

            if (StringUtils.isBlank(dto.getDeviceType()) || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getDeviceUnique())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            switch (dto.getDeviceType()) {
                //云电梯机器人对云端
                case "1":
                    dto.setRobotDevelopDeviceType(2);
                    return sdkCloudElevatorRTLController.getElevatorOftenStatus(dto);
                //云门禁
                case "3":
                    return sdkCloudEntranceController.getEntranceStatus(dto);
                //机器人无感
                case "4":
                    dto.setRobotDevelopDeviceType(1);
                    return sdkCloudElevatorRTLController.getElevatorOftenStatus(dto);

                //云对讲
                case "5":
                    dto.setDeviceType("1");
                    return sdkCloudTalkEquipController.getCloudTalkAppStatus(dto);


                //一体式人脸识别仪（目前设备只集成阿里云）
                case "7":
                    dto.setDeviceType("7");
                    return sdkFaceRecognitionController.getFaceRecognitionStatus(dto);
                //人脸平板
                case "8":
                    dto.setDeviceType("3");
                    return sdkFaceRecognitionController.getFaceRecognitionStatus(dto);

            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),responseTimestamp, dto.getAppSecret()), null);
        } catch (Exception e) {
            throw new DataAccessException("【SDK_基类_gerDeviceStatus】获取设备状态异常", e);
        }
    }


    /**
     * <desc>
     * 电梯楼层开放或登记
     * <desc/>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019/09/17
     */
    @PostMapping(value = "/openOrAutoRegister")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_AUTO_REGISTER)
    @ResponseBody
    public Object openOrAutoRegister() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            dto.setAppId(request.getAttribute("appId").toString());
            dto.setAppSecret(request.getAttribute("appSecret").toString());
            String responseTimestamp = new Date().getTime()+"";
            LOG.info("======openOrAutoRegister电梯楼层开放或登记============入参================>{}",null==dto?"":dto.toString());

            if (StringUtils.isBlank(dto.getDeviceType()) || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getDeviceUnique())
                    || StringUtils.isBlank(dto.getFloors()) || dto.getSeconds() == null) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }

            SDKMessageVO messageVO = null;
            switch (dto.getDeviceType()) {
                //云电梯机器人对云端
                case "1":
                    dto.setRobotDevelopDeviceType(2);
                    messageVO = (SDKMessageVO) sdkCloudElevatorRTLController.publicParamCheck(dto);
                    break;
                //云电梯云端对云端
                case "2":
                    messageVO = (SDKMessageVO) sdkCloudElevatorCTLController.publicParamCheck(dto);
                    break;
            }
            if (messageVO != null) {
                messageVO.setTimestamp(responseTimestamp);
                LOG.info("======openOrAutoRegister电梯楼层开放或登记messageVO============出参================>{}",null==messageVO?"":messageVO.toString());

                return messageVO;
            }

            DeviceElevatorInfoPO po = iCloudElevatorSDKServerCloudServiceClient.getElevatorByDeviceUnique(dto.getDeviceUnique());
            if ("1".equals(dto.getDeviceType())) {//云电梯设备判断,标准版不支持机器人呼梯
                if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 1) {//设备属性配置 ：1标准 2云机器人 3全功能
                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
                }
            } else if ("2".equals(dto.getDeviceType())) {//云电梯设备判断,云机器人版不支持云端功能
                if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 2) {//设备属性配置 ：1标准 2云机器人 3全功能
                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
                }
            }

            //获取真实楼层
            Map<String, Object> floor = iCloudElevatorSDKServerCloudServiceClient.getFloorNumAndNaturalFloorByLogicFloor(dto.getFloors(),
                    dto.getDeviceUnique());
            if (floor == null || floor.get("floors") == null || floor.get("naturals") == null) {
                return new SDKMessageVO(CloudElevarotErrorCodeEnum.CLOUD_FLOOR_ERROR.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            //调用IOT呼梯
            iAppDeviceServiceClient.openOrAutoRegister(dto.getDeviceUnique(),
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    floor.get("floors").toString(), CloudElevatorCallTypeEnum.IN.getType(), dto.getSeconds(), CallElevatorSourceTypeEnum.ROBOT.getType(), "1", null);
            //装配呼梯记录对象
            AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
            saveDTO.setDeviceUnique(dto.getDeviceUnique());
            saveDTO.setToFloor(floor.get("naturals").toString());
            saveDTO.setProjectId(dto.getProjectId());
            saveDTO.setSource(CallElevatorRecordSourceEnum.ROBOT.getType());
            saveDTO.setUserId(dto.getAppId());
            iAppHomeServiceClient.saveCallLiftRecord(saveDTO);
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),dto.getRequestId(),responseTimestamp,Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),responseTimestamp, dto.getAppSecret()));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_openOrAutoRegister】电梯楼层开放或登记异常", e);
        }
    }

    /**
     * <desc>
     * 设置专梯模式
     * <desc/>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019-09-18
     */
    @RequestMapping(value = "/setCloudElevatorSpecialUseModel", method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_BASE_SET_CLOUD_ELEVATOR_SPECIAL_USE_MODEL)
    @ResponseBody
    public Object setCloudElevatorSpecialUseModel() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            dto.setAppId(request.getAttribute("appId").toString());
            dto.setAppSecret(request.getAttribute("appSecret").toString());
            String responseTimestamp = new Date().getTime()+"";
            if (StringUtils.isBlank(dto.getDeviceType()) || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getDeviceUnique())
                    || StringUtils.isBlank(dto.getModel())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            LOG.info("======setCloudElevatorSpecialUseModel设置专梯模式============出参================>{}",null==dto?"":dto.toString());

            SDKMessageVO messageVO = null;
            switch (dto.getDeviceType()) {
                //云电梯机器人对云端
                case "1":
                    dto.setRobotDevelopDeviceType(2);
                    messageVO = (SDKMessageVO) sdkCloudElevatorRTLController.publicParamCheck(dto);
                    break;
                //云电梯云端对云端
                case "2":
                    messageVO = (SDKMessageVO) sdkCloudElevatorCTLController.publicParamCheck(dto);
                    break;
            }
            if (messageVO != null) {
                messageVO.setTimestamp(responseTimestamp);
                LOG.info("======setCloudElevatorSpecialUseModel设置专梯模式messageVO============出参================>{}",null==messageVO?"":messageVO.toString());
                return messageVO;
            }
            DeviceElevatorInfoPO po = iCloudElevatorSDKServerCloudServiceClient.getElevatorByDeviceUnique(dto.getDeviceUnique());
            if ("1".equals(dto.getDeviceType())) {//云电梯设备判断,标准版不支持机器人呼梯
                if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 1) {//设备属性配置 ：1标准 2云机器人 3全功能
                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
                }
            } else if ("2".equals(dto.getDeviceType())) {//云电梯设备判断,云机器人版不支持云端功能
                if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 2) {//设备属性配置 ：1标准 2云机器人 3全功能
                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
                }
            }

            iAppDeviceServiceClient.setCloudElevatorSpecialUseModel(dto.getDeviceUnique(), dto.getModel());
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),dto.getRequestId(),responseTimestamp,Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),responseTimestamp, dto.getAppSecret()));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_setCloudElevatorSpecialUseModel】设置专梯模式异常", e);
        }
    }

    /**
     * <desc>
     *      项目信息列表
     * <desc/>
     *
     * @return  MessageVO   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/05/23
     */
    @RequestMapping(path = "/getProjectInfo", method = RequestMethod.POST)
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_PROJECT_INFO_LOG_DESC)
    @ResponseBody
    public Object getProjectInfo() {
        SDKMessageVO messageVO;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudTalkSDKServerGetProjectInfoPageDTO pageDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerGetProjectInfoPageDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",request.getAttribute("appId").toString());
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            pageDTO.setAppId(request.getAttribute("appId").toString());
            String responseTimestamp = new Date().getTime()+"";
            //判断接入凭证
            if(StringUtils.isBlank(pageDTO.getAppId())){
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),pageDTO.getRequestId(),responseTimestamp,"");
            }
            Page<SDKServerProjectInfoListPageVO> pageVO = iCloudTalkSDKServerProjectServiceClient.getProjectList(pageDTO);
            SDKServerProjectInfoListVO sdkServerProjectInfoListVO = new SDKServerProjectInfoListVO();
            sdkServerProjectInfoListVO.setTotalNumber(pageVO.getPage().getTotalNumber());
            sdkServerProjectInfoListVO.setProjectInfoArr(pageVO.getRows());
            Map<String, Object> signMap = new HashMap<>();
            signMap.put("data", JSON.toJSONString(pageVO));
            messageVO = new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), pageDTO.getRequestId(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(signMap,pageDTO.getRequestId(),responseTimestamp, request.getAttribute("appSecret").toString()), pageVO);
        }catch (Exception e){
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getProjectInfo】获取项目信息列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      添加或更新楼栋信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author jiaqi.X
     * @createDate 2019/11/06
     */
    @ResponseBody
    @PostMapping(path = "/addOrUpdateBuild")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_BUILD_ADD_OR_UPDATE_LOG_DESC)
    public Object addOrUpdateBuilds() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime()+"";
            if(dto==null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getBuildJson())){
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if(dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())){
                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }

            Map<String,Object> result = (HashMap) sdkCloudTalkProjectController.cloudTalkSDKAddOrUpdateBuild(dto);
            Integer count = Integer.valueOf(result.get("count").toString());
            JSONArray errArray = result.get("errArray") != null ? JSONArray.parseArray(result.get("errArray").toString()) : new JSONArray();
            String errStr = "";
            if (errArray.size() > 0) {
                errStr = ",未添加或更新的异常数据：" + errArray.toJSONString();
            }
            if (count > 0) {
                return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                        Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),dto.getResponseTimestamp(), dto.getAppSecret()), (Object) String.format("%s%s", "本次总共添加或更新了：" + count + " 条数据", errStr));
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),dto.getResponseTimestamp(), dto.getAppSecret()), (Object) ("添加的数据已存在,或存在异常的数据" + errStr));

        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addOrUpdateBuilds】添加楼栋信息失败", e);
        }
    }

    /**
     * <desc>
     *      添加或更新单元信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author jiaqi.X
     * @createDate 2019/11/06
     */
    @ResponseBody
    @PostMapping(path = "/addOrUpdateUnit")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_UNIT_ADD_OR_UPDATE_LOG_DESC)
    public Object addOrUpdateUnits() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime()+"";
            if(dto==null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getUnitJson())){
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }

            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if(dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())){
                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }

            Map<String,Object> result = (HashMap) sdkCloudTalkProjectController.cloudTalkSDKAddOrUpdateUnit(dto);
            Integer count = Integer.valueOf(result.get("count").toString());
            JSONArray errArray = result.get("errArray") != null ? JSONArray.parseArray(result.get("errArray").toString()) : new JSONArray();
            String errStr = "";
            if (errArray.size() > 0) {
                errStr = ",未添加或更新的异常数据：" + errArray.toJSONString();
            }
            if (count > 0) {
                return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                        Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),dto.getResponseTimestamp(), dto.getAppSecret()), (Object) String.format("%s%s", "本次总共添加或更新了：" + count + " 条数据", errStr));
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),dto.getResponseTimestamp(), dto.getAppSecret()), (Object) ("添加的数据已存在,或存在异常的数据" + errStr));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addOrUpdateUnits】添加单元信息失败", e);
        }
    }


    /**
     * <desc>
     *      添加或修改房间信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author jiaqi.X
     * @createDate 2019/11/06
     */
    @ResponseBody
    @PostMapping(path = "/addOrUpdateRoom")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ROOM_ADD_OR_UPDATE_LOG_DESC)
    public Object addOrUpdateRooms() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime()+"";
            if(dto==null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getRoomJson())){
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if(dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())){
                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }

            //云对讲
            Map<String,Object> result = (HashMap) sdkCloudTalkProjectController.cloudTalkSDKAddOrUpdateRoom(dto);
            Integer count = Integer.valueOf(result.get("count").toString());
            JSONArray errArray = result.get("errArray") != null ? JSONArray.parseArray(result.get("errArray").toString()) : new JSONArray();
            String errStr = "";
            if (errArray.size() > 0) {
                errStr = ",未添加或更新的异常数据：" + errArray.toJSONString();
            }
            if (count > 0) {
                return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                        Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),dto.getResponseTimestamp(), dto.getAppSecret()), (Object) String.format("%s%s", "本次总共添加或更新了：" + count + " 条数据", errStr));
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),dto.getResponseTimestamp(), dto.getAppSecret()), (Object) ("添加的数据已存在,或存在异常的数据" + errStr));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addOrUpdateRooms】添加或更新房间信息失败", e);
        }
    }

    /**
     * <desc>
     *      查询项目楼栋信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/07
     */
    @ResponseBody
    @PostMapping(path = "/getBuildList")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_BUILD_GET_LIST_LOG_DESC)
    public Object getBuildList() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime()+"";
            dto.setResponseTimestamp(responseTimestamp);
            if(dto==null || StringUtils.isBlank(dto.getProjectId())){
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
            }
            if (StringUtils.isBlank(dto.getCurrentPage())) {
                dto.setCurrentPage("1");
            }
            if (StringUtils.isBlank(dto.getPageSize())) {
                dto.setPageSize("15");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if(dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())){
                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }
            return sdkCloudTalkProjectController.getBuildList(dto);

        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getBuildList】获取项目楼栋信息失败", e);
        }
    }

    /**
     * <desc>
     *      获取项目楼栋的单元信息列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/08
     */
    @ResponseBody
    @PostMapping(path = "/getUnitList")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_UNIT_GET_LIST_LOG_DESC)
    public Object getUnitList() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime()+"";
            dto.setResponseTimestamp(responseTimestamp);
            if(dto==null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getBuildNum())){
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
            }
            if (StringUtils.isBlank(dto.getCurrentPage())) {
                dto.setCurrentPage("1");
            }
            if (StringUtils.isBlank(dto.getPageSize())) {
                dto.setPageSize("15");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if(dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())){
                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }
            return sdkCloudTalkProjectController.getUnitList(dto);

        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getUnitList】获取项目楼栋单元信息失败", e);
        }
    }

    /**
     * <desc>
     *      获取项目房间信息列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/08
     */
    @ResponseBody
    @PostMapping(path = "/getRoomList")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ROOM_GET_LIST_LOG_DESC)
    public Object getRoomList() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            String responseTimestamp = new Date().getTime()+"";
            dto.setResponseTimestamp(responseTimestamp);
            if(dto==null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getBuildNum())){
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
            }
            if (StringUtils.isBlank(dto.getCurrentPage())) {
                dto.setCurrentPage("1");
            }
            if (StringUtils.isBlank(dto.getPageSize())) {
                dto.setPageSize("15");
            }
            //如果为人脸识别API则需鉴权
//            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
//                //权限判断
//                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
//                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
//                }
//                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
//            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            if(dto.getDeviceType() != null && dto.getDeviceType().equals(SdkSourceTypeEnum.CLOUD_TALK.getType())){
                request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            }
            return sdkCloudTalkProjectController.getRoomList(dto);

        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getRoomList】获取项目房间信息失败", e);
        }
    }

    /**
     * <desc>
     *      批量往存在的房间中添加住户
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author jiaqi.X
     * @createDate 2019/11/06
     */
    @ResponseBody
    @PostMapping(path = "/userRoom/add")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_BATCH_SAVE_USER_LOG_DESC)
    public Object addOrUpdateUserRooms() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", request.getAttribute("appId").toString() + "|" + dto.getProjectId() + "|" + dto.getDeviceType());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            String responseTimestamp = new Date().getTime()+"";
            if(dto.getDeviceType().equals("5")) {
                //云对讲
//                Map<String,Object> returnData = (HashMap) sdkCloudTalkProjectController.cloudTalkSDKAddUser(dto);
//                String code = returnData.get("code").toString();
//                if(code.equals("0")){
//                    return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),dto.getRequestId(),responseTimestamp,Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),responseTimestamp, dto.getAppSecret()), returnData);
//                }else{
//                    return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),dto.getRequestId(),responseTimestamp,Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),responseTimestamp, dto.getAppSecret()), (Object) returnData.get("modifyMessage").toString());
//                }
                return sdkCloudTalkProjectController.cloudTalkSDKAddUser(dto);
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),dto.getRequestId(),responseTimestamp,Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),dto.getRequestId(),responseTimestamp, dto.getAppSecret()));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addOrUpdateRooms】添加或更新房间信息失败", e);
        }
    }

    /**
     * <desc>
     *      查询通行记录
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/11
     */
    @ResponseBody
    @PostMapping(path = "/getRecordInfo")
//    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_PASS_RECORD_LOG_DESC)
    public Object getPassRecord() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            String responseTimestamp = new Date().getTime()+"";
            dto.setResponseTimestamp(responseTimestamp);
            if (dto == null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getUserType()) || StringUtils.isBlank(dto.getRecordType()) || StringUtils.isBlank(dto.getDeviceType())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),request.getAttribute("requestId").toString(),responseTimestamp,"");
            }

            if (StringUtils.isBlank(dto.getCurrentPage())) {
                dto.setCurrentPage("1");
            }
            if (StringUtils.isBlank(dto.getPageSize())) {
                dto.setPageSize("15");
            }

            switch (SdkSourceTypeEnum.getByEquipType(Integer.valueOf(dto.getDeviceType()))) {
                //云对讲
                case CLOUD_TALK:
                    return sdkCloudTalkUserController.getPassRecord(dto);
                //二维码sdk
                case QR_CODE_SDK:
                    QrcodeSDKGetPassRecordDTO qrcodeSDKGetPassRecordDTO = HttpProtocolUtil.parseRequestParamToDTO(QrcodeSDKGetPassRecordDTO.class, request);
                    qrcodeSDKGetPassRecordDTO.setAppid(dto.getAppId());
                    qrcodeSDKGetPassRecordDTO.setAppsecret(dto.getAppSecret());
                    qrcodeSDKGetPassRecordDTO.setRequestId(dto.getRequestId());
                    qrcodeSDKGetPassRecordDTO.setResponseTimestamp(dto.getResponseTimestamp());
                    return sdkQrCodeController.getPassRecord(qrcodeSDKGetPassRecordDTO);
                //人脸识别sdk
                case FACE_SDK:
                    //权限判断
                    OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
                    operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
                    operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
                    OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
                    if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
                        return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
                    }
                    dto.setFaceMark("1");
                    request.setAttribute("portType",  LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
                    return sdkFaceRecognitionController.getPassRecord(dto);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_getRecordInfo】查询通行记录失败", e);
        }
    }

    /**
     * <desc>
     *      添加或更新多媒体资源信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/11
     */
    @ResponseBody
    @PostMapping(path = "/addOrUpdateMedia")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_MEDIA_ADD_OR_UPDATE_LOG_DESC)
    public Object addOrUpdateMedia() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudTalkSDKServerMediaDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerMediaDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            String responseTimestamp = new Date().getTime() + "";
            dto.setResponseTimestamp(responseTimestamp);
            if(StringUtils.isBlank(dto.getDeviceType())){
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
            }

            switch (dto.getDeviceType()) {
                //云对讲
                case "5":
                    return sdkCloudTalkMediaController.cloudTalkSDKAddOrUpdateMedia(dto);
                case "7":
                    //权限判断
                    OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
                    operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
                    operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
                    OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
                    if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
                        return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
                    }
                    request.setAttribute("portType", LogDescConstant.SDK_CLOUD_FACE_RECOGNITION_TYPE_LOG_DESC);
                default:
            }
            return sdkCloudTalkMediaController.cloudTalkSDKAddOrUpdateMedia(dto);
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addOrUpdateMedia】添加或更新多媒体资源信息失败", e);
        }
    }

    /**
     * <desc>
     *      添加访客
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/11/18
     */
    @ResponseBody
    @PostMapping(path = "/addVisitorInfo")
    @LoggerInfo(operateDesc = LogDescConstant.SAVE_VISITOR_INFO_DESC)
    public Object addVisitor() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            PropertyAddVisitorDTO dto = HttpProtocolUtil.parseRequestParamToDTO(PropertyAddVisitorDTO.class, request);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
            String responseTimestamp = new Date().getTime()+"";
            if (dto == null || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getIntervieweeName()) || StringUtils.isBlank(dto.getVisitorName())
                    || StringUtils.isBlank(dto.getEffectiveTime()) || StringUtils.isBlank(dto.getDeviceType())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            //校验所传地址在该项目下是否存在
            Map<String,Object> map = iFaceSDKVisitorServiceClient.getAddressInfo(dto);
            if(map ==null || map.isEmpty()){
                return new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_NOT_EXIST_ROOMNUM_ERR.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            //校验访客姓名及被拜访访客姓名的字段长度
            if(dto.getVisitorName().length()>32 || dto.getIntervieweeName().length()>32){
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_VISITOR_NAME_ERR.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            if(dto.getDeviceType().equals(SdkSourceTypeEnum.FACE_SDK.getType().toString())){
                if (StringUtils.isBlank(dto.getRoomId()) || StringUtils.isBlank(dto.getBuildId()) || StringUtils.isBlank(dto.getUnitId())
                        || StringUtils.isBlank(dto.getImageStr())) {
                    return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
                }
                //权限判断
                OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
                operateDeveloperAuthDeviceAuthListDTO.setUserId(dto.getAppId());
                operateDeveloperAuthDeviceAuthListDTO.setProjectId(dto.getProjectId());
                OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
                if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
                    return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
                }
            }else{
                if (StringUtils.isBlank(dto.getRoomNum()) || StringUtils.isBlank(dto.getBuildNum()) || StringUtils.isBlank(dto.getUnitNum())) {
                    return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
                }
                dto.setBuildId(map.get("buildId").toString());
                dto.setUnitId(map.get("unitId").toString());
                dto.setRoomId(map.get("roomId").toString());
            }
            return sdkFaceRecognitionController.addVisitor(dto);
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_基类_addVisitorInfo】添加访客失败", e);
        }
    }

    public static void main(String[] args) {
        String s = null;
        switch (s) {
            //云对讲
            case "5":
                System.out.println("2");
            default:
                System.out.println("1");
        }
    }

    /**
     * <desc>
     *      冻结/解冻用户状态
     * <desc/>
     *
     * @return  MessageVO   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/11/19
     */
    @ResponseBody
    @PostMapping(path="/modifyUserStatus")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_FACE_USER_PROJECT_STATUS_LOG_DESC)
    public Object modifyUserStatus() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            dto.setAppId(request.getAttribute("appId").toString());
            dto.setAppSecret(request.getAttribute("appSecret").toString());
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", dto.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);

            String responseTimestamp = new Date().getTime()+"";
            if (StringUtils.isBlank(dto.getProjectId())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),dto.getRequestId(),responseTimestamp,"");
            }
            switch (dto.getDeviceType()) {
                //云对讲
                case "5":
                    CloudTalkSDKServerUserStatusDTO userStatusDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerUserStatusDTO.class, request);
                    userStatusDTO.setAppSecret(dto.getAppSecret());
                    userStatusDTO.setResponseTimestamp(responseTimestamp);
                    userStatusDTO.setRequestId(dto.getRequestId());
                    return sdkCloudTalkProjectController.modifyUserStatus(userStatusDTO);
                default:
                    //公共
                    AppUserUpdateUserProjectStatusDTO appUserUpdateUserProjectStatusDTO = HttpProtocolUtil.parseRequestParamToDTO(AppUserUpdateUserProjectStatusDTO.class, request);
                    appUserUpdateUserProjectStatusDTO.setProjectId(request.getAttribute("projectId").toString());
                    appUserUpdateUserProjectStatusDTO.setAppSecret(dto.getAppSecret());
                    appUserUpdateUserProjectStatusDTO.setResponseTimestamp(responseTimestamp);
                    appUserUpdateUserProjectStatusDTO.setRequestId(dto.getRequestId());
                    //权限判断
//                    OperateDeveloperAuthDeviceAuthListDTO operateDeveloperAuthDeviceAuthListDTO = new OperateDeveloperAuthDeviceAuthListDTO();
//                    operateDeveloperAuthDeviceAuthListDTO.setUserId(request.getAttribute("appId").toString());
//                    operateDeveloperAuthDeviceAuthListDTO.setProjectId(appUserUpdateUserProjectStatusDTO.getProjectId());
//                    OperateDeveloperAuthDeviceAuthVO operateDeveloperAuthDeviceAuthVO = iOperateDeveloperAuthServiceClient.deviceAuthList(operateDeveloperAuthDeviceAuthListDTO);
//                    if (operateDeveloperAuthDeviceAuthVO == null || operateDeveloperAuthDeviceAuthVO.getFaceRecognitionApi() != 1) {//没有权限
//                        return new SDKMessageVO(SDKErrorCodeEnum.SDK_FACE_API_AUTHORITY_ERR.getErrorCode(), dto.getRequestId(), responseTimestamp, "");
//                    }
                    return sdkFaceRecognitionController.modifyUserStatus(appUserUpdateUserProjectStatusDTO);
            }
        } catch (Exception e) {
            throw new DataAccessException("【SDK_基类_modifyUserStatus】冻结/解冻用户状态异常", e);
        }
    }

    /**
     * <desc>
     *      机器人调试工具开发者登录
     * </desc>
     *
     * @return
     * @Author Zhu.yj
     * @createDate  2020/8/25
     */
    @UnAuthAccessRequired
    @RequestMapping(value = "robotGoDeveloperLogin", method = RequestMethod.POST)
    public Object robotGoDeveloperLogin(String encryptScript,String appId, String loginType){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        String responseTimestamp = new Date().getTime()+"";
        Date nowDate = new Date();
        Map<String, Object> resultMap = new HashMap<>();
        PropertyUserInfoPO propertyUserInfoPO = new PropertyUserInfoPO();
        try {
            if (StringUtils.isBlank(loginType) || StringUtils.isBlank(appId) || StringUtils.isBlank(encryptScript)) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), "", responseTimestamp, "");
            }
            //开发者登录
            if ("1".equals(loginType)) {
                //当登录类型位开发者登录的时候
                propertyUserInfoPO = iSDKUserServiceClient.getPropertyUserByUserName(appId);
                if (propertyUserInfoPO == null || StringUtils.isBlank(propertyUserInfoPO.getAppsecret())) {
                    return new SDKMessageVO(AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode(), "", responseTimestamp, "");//此时没有加密签名直接明文返回报错信息
                }
                propertyUserInfoPO.setAppsecret(APP_SECRET);
                if (propertyUserInfoPO.getStatus() != DataStatusEnum.NORMAL.getType()) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(AppErrorCodeEnum.ACCOUNT_BAN_ERROR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                //未开通机器人调试开关
                if (propertyUserInfoPO.getRobotSwitch() == 0) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.PUB_ROBOT_SWITCH_CLOSE_ERR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                //不在有效期内
                if (nowDate.before(propertyUserInfoPO.getEffectStartTime()) || nowDate.after(propertyUserInfoPO.getEffectEndTime())) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_ACCOUNT_EXPIRE_ERR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                //筛选只有机器人开发者有权限
                if (!propertyUserInfoPO.getRoleId().equals(PropertyPublicRoleEnum.ROBOT_DEVELOPER.getRoleId())) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_AUTH_ERROR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
            }
            if ("2".equals(loginType)) {
                OperateUserInfoPO operateUserInfoPO = iOperateUserInfoServiceClient.getUserByUserName(appId);
                //把工程人员的信息存到propertyUserInfo中，为方便存储缓存
                if (operateUserInfoPO == null) {
                    //此时没有加密签名直接明文返回报错信息
                    return new SDKMessageVO(AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode(), "", responseTimestamp, "");
                }
                //工程账号不再有效期内
                if (operateUserInfoPO.getAuthType() == 1 && (nowDate.before(operateUserInfoPO.getAuthStartTime()) || nowDate.after(operateUserInfoPO.getAuthEndTime()))){
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_ACCOUNT_EXPIRE_ERR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                BeanUtils.copyProperties(operateUserInfoPO, propertyUserInfoPO);
                propertyUserInfoPO.setAppsecret(APP_SECRET);
                if (null == propertyUserInfoPO.getRoleId()) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_AUTH_ERROR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }

                List<String> roleIdList = StringHandlerUtil.splitStringList(propertyUserInfoPO.getRoleId());
                if (!roleIdList.contains(OperateSystemSetUpEnum.ENGINNER.getType().toString())) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_AUTH_ERROR.getErrorCode(), "", responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                //工程人员设置roleId为1,否则拿不到数据
                propertyUserInfoPO.setRoleId(OperateSystemSetUpEnum.ENGINNER.getType().toString());
            }
            CloudDeviceSDKDTO dto = new CloudDeviceSDKDTO();
            String encryptResult = DesEncryptUtil.aesDecrypt(encryptScript, propertyUserInfoPO.getAppsecret());
            if (StringUtils.isBlank(encryptResult)) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_PARAM_APPID_APPSECRET_ERR.getErrorCode(), "", responseTimestamp, "");//此时没有加密签名直接明文返回报错信息
            }
            Map<String, Object> params;
            JSONObject jsStr = JSONObject.parseObject(encryptResult);//入参转json
            String requestId;
            try {
                requestId = jsStr.get("requestId") == null ? "" : jsStr.get("requestId").toString();
                String timestamp = jsStr.get("timestamp") == null ? "" : jsStr.get("timestamp").toString();
                request.setAttribute("requestId", requestId);
                request.setAttribute("timestamp", timestamp);
                JSONObject protocol = JSONObject.parseObject(jsStr.get("protocol").toString());
                request.setAttribute("version", protocol.get("version") == null ? "" : protocol.get("version").toString());
                JSONObject client = JSONObject.parseObject(jsStr.get("client").toString());
                JSONObject param = JSONObject.parseObject(jsStr.get("param").toString());
                params = JsonUtil.toObject(protocol.toString(), HashMap.class);
                params.putAll(JsonUtil.toObject(client.toString(), HashMap.class));
                params.putAll(JsonUtil.toObject(param.toString(), HashMap.class));

                //保存生成操作日志所需信息 详细描述和接口类别
//                request.setAttribute("remark", "appId:"+appId + "|" + "appSecret:"+params.get("appSecret") + "robotId:"+param.get("robotId"));
//                request.setAttribute("portType", LogDescConstant.SDK_CLOUD_DEVICE_TYPE_LOG_DESC);
//                dto.setAppId(appId);
//                dto.setAppSecret(params.get("appSecret").toString());
                params.remove("appSecret");

                //验签
                String sign = jsStr.get("sign").toString();
                if (!Md5EncryptUtil.checkSDKV2Sign(params, sign, requestId, timestamp, propertyUserInfoPO.getAppsecret())) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(CloudTalkErrorCodeEnum.SERVER_MD5_ERROR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
            } catch (Exception e) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_INPUT_PARAM_ERR.getErrorCode(), "", responseTimestamp, "");//json格式解析失败
            }
            String password = params.get("password") == null ? null : params.get("password").toString();
            String robotUnique = params.get("robotUnique") == null ? null : params.get("robotUnique").toString();
            if (StringUtils.isBlank(password) || StringUtils.isBlank(robotUnique)) {
                return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
            }
            //验证密码是否正确
            password = UserTokenUtil.getPassword(password, APP_USER_TOKEN_KEY);
            if (!Md5.En(password).equals(propertyUserInfoPO.getPassword())) {
                return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
            }
            //获取登录个
            PropertyUserInfoPO userRetrieveInfoPO = (PropertyUserInfoPO) redisService.getObject(RedisConstant.REDIS_CLOUDDEVICE_SDK_DEVELOPER_CACHE + propertyUserInfoPO.getUserId(), PropertyUserInfoPO.class);
            //做登录个数限制
            if (userRetrieveInfoPO == null) {
                userRetrieveInfoPO = new PropertyUserInfoPO();
            }
            List<String> robotUniques = userRetrieveInfoPO.getRobotUniques();
            if (robotUniques == null) {
                robotUniques = new ArrayList<>();
                robotUniques.add(robotUnique);
            }
            if (!robotUniques.contains(robotUnique)) {
                robotUniques.add(robotUnique);
            }
            if ("1".equals(loginType)) {
                if (robotUniques.size() > propertyUserInfoPO.getLoginCount()) {
                    return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(AppErrorCodeEnum.ROBOT_LOGIN_COUNT_ERR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                }
                resultMap.put("statTime", dateFormat.format(propertyUserInfoPO.getEffectStartTime()));
                resultMap.put("stopTime", dateFormat.format(propertyUserInfoPO.getEffectEndTime()));
            } else {
                resultMap.put("statTime", "永久有效");
                resultMap.put("stopTime", "永久有效");
            }
            propertyUserInfoPO.setRobotUniques(robotUniques);
            propertyUserInfoPO.setLoginType(loginType);
            String token = iCloudTalkSDKAppUserServiceClient.robotGoDeveloperLogin(propertyUserInfoPO, null);
            List<AppProjectRobotInfoVO> projectRobotInfoVOS = iOperatePropertyAccountServiceClient.getProjectRobotInfoByDeveloper(propertyUserInfoPO.getUserId(), loginType);
            if ("1".equals(loginType)) {
                for (AppProjectRobotInfoVO VO : projectRobotInfoVOS){
                    Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(VO.getProjectId(), propertyUserInfoPO.getUserId());
                Integer robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");

                //启用白名单1
                if ("1".equals(robotWhiteListAuthStatus + "")) {
                    //对接方式为云对接，又无项目及机器人信息
                    if ("1".equals(propertyUserInfoPO.getDockMode()) && projectRobotInfoVOS.isEmpty()) {
                        return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(OperateErrorCodeEnum.USER_AUTH_ERROR.getErrorCode(), requestId, responseTimestamp, ""), propertyUserInfoPO.getAppsecret());
                    }
                }
                //没有启用白名单0
                if ("0".equals(robotWhiteListAuthStatus + "")) {
                    List<String> emptyList = new ArrayList<>();
                    VO.setRobotIdList(emptyList);
                }
            }
        }
            resultMap.put("token",token);
            resultMap.put("projectList", projectRobotInfoVOS);
            return DesEncryptUtil.getEncryptResultSDKV2(new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),requestId,responseTimestamp,"", resultMap), propertyUserInfoPO.getAppsecret());
        }catch (Exception e){
            throw new DataAccessException("【SDK_基类_robotGoDeveloperLogin】机器人调试工具开发者登录失败", e);
        }
    }

    /**
     * <desc>
     *      获取项目列表
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2020/8/3
     */
    @ResponseBody
    @PostMapping("getProjectList")
    public Object getProjectList(String token, HttpServletRequest request){
        try {
            String responseTimestamp = new Date().getTime()+"";
            PropertyUserInfoPO propertyUserInfoPO = iCloudTalkSDKAppUserServiceClient.developerRetrieve(token);
            List<AppProjectRobotInfoVO> projectInfoVOList = iOperatePropertyAccountServiceClient.getProjectRobotInfoByDeveloper(propertyUserInfoPO.getUserId(), propertyUserInfoPO.getLoginType());

              if ("4".equals(propertyUserInfoPO.getRoleId()) || "7".equals(propertyUserInfoPO.getRoleId()))
                for (AppProjectRobotInfoVO VO : projectInfoVOList) {
                    Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(VO.getProjectId(), propertyUserInfoPO.getUserId());
                    Integer robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");

                    //没有启用白名单0
                    if ("0".equals(robotWhiteListAuthStatus + "")) {
                        List<String> emptyList = new ArrayList<>();
                        VO.setRobotIdList(emptyList);
                    }
                }
                    return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),request.getAttribute("requestId").toString(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),request.getAttribute("requestId").toString(),responseTimestamp,
                            propertyUserInfoPO.getAppsecret()),projectInfoVOList);
        }catch (Exception e){
            throw new DataAccessException("【SDK_基类_getProjectList】获取项目列表失败", e);
        }
    }

//    /**
//     * <desc>
//     *      切换项目
//     * </desc>
//     *
//     * @return
//     * @Author Zhu.yj
//     * @createDate  2020/8/4
//     */
//    @ResponseBody
//    @PostMapping("changeProject")
//    public Object changeProject(String token, String projectId, HttpServletRequest request){
//        try{
//            String responseTimestamp = new Date().getTime()+"";
//            Map<String, Object> resultMap = new HashMap<>();
//            PropertyUserInfoPO propertyUserInfoPO = iCloudTalkSDKAppUserServiceClient.developerRetrieve(token);
//            if (StringUtils.isBlank(projectId)){
//                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(),request.getAttribute("requestId").toString(), responseTimestamp,
//                        Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),request.getAttribute("requestId").toString(),responseTimestamp,
//                                propertyUserInfoPO.getAppsecret()));
//            }
//
//            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
//        }catch (Exception e){
//            throw new DataAccessException("【APP_切换项目】切换项目失败", e);
//        }
//    }

    /**
     * <desc>
     *      机器人APP退出登录
     * </desc>
     *
     * @param token 登录token
     * @param robotUnique 机器人唯一码
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/10/15
     */
    @ResponseBody
    @PostMapping("logout")
    public Object robotLogout(String token, String robotUnique, HttpServletRequest request){
        try {
            String responseTimestamp = new Date().getTime()+"";
            robotUnique = request.getAttribute("robotUnique") == null ? null : request.getAttribute("robotUnique").toString();
            PropertyUserInfoPO propertyUserInfoPO = iCloudTalkSDKAppUserServiceClient.developerRetrieve(token);
            String cacheKey = String.format("%s%s", RedisConstant.REDIS_CLOUDDEVICE_SDK_DEVELOPER_CACHE, propertyUserInfoPO.getUserId());
            List<String> robotUniques = propertyUserInfoPO.getRobotUniques();
            if (robotUniques != null && robotUniques.size() > 0) {
                robotUniques.remove(robotUnique);
                if (robotUniques.size() > 0) {
                    propertyUserInfoPO.setRobotUniques(robotUniques);
                    redisService.set(cacheKey,RedisConstant.REDIS_ROBOT_USER_CACHE_TIME,propertyUserInfoPO);
                } else {
                    redisService.del(cacheKey);
                }
            } else {
                redisService.del(cacheKey);
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),request.getAttribute("requestId").toString(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),request.getAttribute("requestId").toString(),responseTimestamp,
                            propertyUserInfoPO.getAppsecret()));
        } catch (Exception e) {
            throw new DataAccessException("【SDK基类_机器人退出登录】退出登录失败",e);
        }
    }

    /**
     * <desc>
     *      获取单梯多梯标记
     * </desc>
     *
     * @Author Zhu.yj
     * @createDate  2020/9/7
     */
//    接口暂时注释，下个版本添加
//    @RequestMapping(value = "getElevatorFlag", method = RequestMethod.POST)
    public Object getElevatorFlag(String token, String robotId, HttpServletRequest request){
        try{
            String responseTimestamp = System.currentTimeMillis() + "";
            Map<String, Object> resultMap = new HashMap<>();
            robotId = request.getAttribute("robotId") == null ? null : request.getAttribute("robotId").toString();
            PropertyUserInfoPO propertyUserInfoPO = iCloudTalkSDKAppUserServiceClient.developerRetrieve(token);
            if (robotId == null){
                resultMap.put("flag",MultiElevatorAuthEnum.NONE_ELEVATOR_AUTH.getType());
                return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),request.getAttribute("requestId").toString(), responseTimestamp,
                        Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),request.getAttribute("requestId").toString(),responseTimestamp,
                                request.getAttribute("appSecret").toString()),resultMap);
            }
            resultMap = iCloudElevatorSDKRobotServiceClient.getElevatorFlag(robotId);
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),request.getAttribute("requestId").toString(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),request.getAttribute("requestId").toString(),responseTimestamp,
                            request.getAttribute("appSecret").toString()),resultMap);
        }catch(Exception e){
            throw new DataAccessException("【SDK基类_getElevatorFlag】获取单梯多梯标记失败", e);
        }
    }
    /**
     *<desc>
     * 设置消息回调的url地址
     *</desc>
     *
     * @Author  chengshican
     * @Date   2020-11-19 19:27
     * @Param updateMessageCallbackRrl 用户设置消息推送的接口url
     * @Return
     * @Exception
     *
     */
    @ResponseBody
    @PostMapping("/updateUserProjectByUserId")
   public Object updateUserProjectByUserId(String callbackUrl, String token){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            callbackUrl = request.getAttribute("callbackUrl") == null ? null : request.getAttribute("callbackUrl").toString();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
              PropertyUserInfoPO propertyUserInfoPO = iCloudTalkSDKAppUserServiceClient.developerRetrieve(token);
        //验签
              if (StringUtils.isBlank(callbackUrl) || StringUtils.isBlank(callbackUrl)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            iCloudTalkSDKAppUserServiceClient.updateUserProjectByUserId(callbackUrl,propertyUserInfoPO.getCurrentProjectId(),propertyUserInfoPO.getUserId());
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【SDK基类_updateUserProjectByUserId】设置消息回调的url地址失败", e);
        }
    }



     /**
     *<desc>
     * 触发向第三方推送api接口文档更新接口（开放平台推送更新按钮）
     *</desc>
     *
     * @Author  chengshican
     * @Date   2020-11-23 9:50
     * @Param   0 云对讲 1 蓝牙SDK  2 二维码SDK 3 云电梯API 4 云门禁API 5 人脸识别API 6 机器人无感通行 7 机器人无感通行 8 机器人云门禁 9 离线二维码SDK
     * *         10微信小插件二维码  11微信小插件蓝牙 12 在线二维码API
      * @Param newVersion 版本号
      * @Return
     * @Exception
     *
     */
    @RequestMapping(value = "/pushMessage",method = RequestMethod.POST)
    @ResponseBody
    @UnAuthAccessRequired
    public Object sendPushMessage(String type,String newVersion){
            try {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                type = request.getAttribute("type") == null ? null : request.getAttribute("type").toString();
                newVersion = request.getAttribute("newVersion") == null ? null :request.getAttribute("newVersion").toString();

                //验签
                if (StringUtils.isBlank(type) || StringUtils.isBlank(type)) {
                    return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                //验签
                if (StringUtils.isBlank(String.valueOf(newVersion)) || StringUtils.isBlank(String.valueOf(newVersion))) {
                    return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                Integer num = isdkServerProjectServiceClient.getSendMessgeUrl(type,Double.parseDouble(newVersion));
                if (num>0){
                    return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
                }
                else {
                    return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
                }
            } catch (Exception e) {
                throw new DataAccessException("【SDK基类_sendPushMessage】触发向第三方推送api接口文档更新接口失败", e);
            }
    }

     
     /**
     *<desc>
     * 用户确认接受更新接口（用户接受更新时调用此接口回传信息）
     *</desc>
     *
     * @Author  chengshican
     * @Date   2020-11-23 9:58
     * @Param  
     * @Return      
     * @Exception   
     * 
     */
    @RequestMapping("/pushMessageCallBack")
    @ResponseBody
    @UnAuthAccessRequired
    public Object sendPushMessageCallBack(SendPushMessageDTO dto){
        try {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
           dto = HttpProtocolUtil.parseRequestParamToDTO(SendPushMessageDTO.class, request);
            //验签
            if (StringUtils.isBlank(dto.getLoginUserId()) || dto==null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Integer integer = isdkServerProjectServiceClient.updateSDKApiVersion(dto);
            if (integer>0){
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }
            else {
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【SDK基类_sendPushMessageCallBack】用户确认接受更新接口失败", e);
        }
    }




    /**
     *<desc>
     * 测试用户接受更新接口
     *</desc>
     *
     * @Author  chengshican
     * @Date   2020-11-23 9:58
     * @Param
     * @Return
     * @Exception
     *
     */
    @RequestMapping("/sendPushMessageCallBackTest")
    @ResponseBody
    @UnAuthAccessRequired
    public Object sendPushMessageCallBackTest(@RequestParam(required=false, defaultValue="1") String id){
        try {
            LOG.info("==1===========id=====>{}",id);
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String id1 = request.getParameter("id");
            LOG.info("===2==========id=====>{}",id1);
            return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【SDK基类_sendPushMessageCallBackTest】测试用户接受更新接口", e);
        }
    }

    /**
     * <desc>
     *      修改用户（包含用户基本信息及房间变更）
     * </desc>
     *
     * @param token 登录token
     * @param appUserGetUserInfo 用户信息传输数据
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2021/06/16
     */
    @ResponseBody
    @PostMapping("updateUserInfo")
    public Object updateUserInfo(String token, String appUserGetUserInfo,String imageStr,String projectId,String loginUserId, HttpServletRequest request){
        try {
            String responseTimestamp = new Date().getTime()+"";
            appUserGetUserInfo = request.getAttribute("appUserGetUserInfo") == null ? null : request.getAttribute("appUserGetUserInfo").toString();
            String requestId = request.getAttribute("requestId") == null ? null : request.getAttribute("requestId").toString();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            imageStr = request.getAttribute("imageStr") == null ? null : request.getAttribute("imageStr").toString();
            //参数合法性判断
            if (StringUtils.isBlank(projectId)) {
                return new SDKMessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode(),requestId,responseTimestamp,"");
            }
            if (StringUtils.isEmpty(appUserGetUserInfo)) {
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_USERINFO_NOT_NULL.getErrorCode(),requestId,responseTimestamp,"");
            }
            AppUserGetUserInfoDTO appUserGetUserInfoDTO;
            try {
                appUserGetUserInfoDTO = JSON.parseObject(appUserGetUserInfo, AppUserGetUserInfoDTO.class);
            } catch (Exception e) {
                throw new DataAccessException("【物业系统_住户信息管理_更新住户信息】数据格式有误", e);
            }
            if (appUserGetUserInfoDTO == null) {
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_USERINFO_NOT_NULL.getErrorCode(),requestId,responseTimestamp,"");
            }
            appUserGetUserInfoDTO.setImageStr(imageStr);
            PropertyUserInfoPO propertyUserInfoPO = iCloudTalkSDKAppUserServiceClient.developerRetrieve(token);
            appUserGetUserInfoDTO.setProjectId(projectId);
            String userId = appUserGetUserInfoDTO.getUserId();
            //用户不能为空
            if (StringUtils.isBlank(userId)) {
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_CHOICEUSER_NOT_NULL.getErrorCode(),requestId,responseTimestamp,"");
            }
            //用户姓名不能为空
            if (StringUtils.isEmpty(appUserGetUserInfoDTO.getRealName())) {
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_REALNAME_NOT_NULL.getErrorCode(),requestId,responseTimestamp,"");
            }
            //用户手机号合法性判断
            String phoneNum = appUserGetUserInfoDTO.getPhoneNum();
            if (StringUtils.isBlank(phoneNum)) {
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_PHONENUM_NOT_NULL.getErrorCode(),requestId,responseTimestamp,"");
            }
            //校验权限信息是否为空
            if (StringUtils.isBlank(appUserGetUserInfoDTO.getAuthInfo())){
                return new SDKMessageVO(PropertyErrorCodeEnum.PROPERTY_AUTH_INFO_NOT_NULL_ERR.getErrorCode(),requestId,responseTimestamp,"");
            }

            List<AppUserRoomDTO> appUserRoomDTOS = new ArrayList<>();
            //分解地址授权信息和角色组授权信息
            List<String> roleIdList = this.divideAddressAndRoleAuth( appUserRoomDTOS, appUserGetUserInfoDTO);
            if(roleIdList!=null && roleIdList.size()==1 && roleIdList.get(0).startsWith("楼栋编号")){
                return new SDKMessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(),roleIdList.get(0),requestId,responseTimestamp,"");
            }

            appUserGetUserInfoDTO.setAppUserRoomDTOS(appUserRoomDTOS);
            //判断用户该项目下是否存在
            if(iPropertyHouseHoldInfoServiceClient.getUserIsExist(projectId, userId)==0){
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_IS_NOT_EXIST_ERROR.getErrorCode(),requestId,responseTimestamp,"");
            }
            //住户项目数据状态正常时，若住户已被冻结，则无法迁入
            Integer userProjectStatus = iPropertyHouseHoldInfoServiceClient.getUserProjectStatusAtNormal(projectId, userId);
            if (AppUserProjectStatusEnum.USERPROJECT_USERPROJECTSTATUS_FROZEN.getType() == userProjectStatus) {
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_USERPROJECTSTATUS_FROZEN.getErrorCode(),requestId,responseTimestamp,"");
            }
            //判断住户业主房间地址中是否已存在业主
            //Map<String, value> ：isExist业主是否存在，roomNum 业主存在时的房间号,userId 业主userId
            Map<String, String> resultMap = this.checkOwnerExist(appUserRoomDTOS);
            String isExist = resultMap.get("isExist");
            //房间存在业主，且房间中的业主与当前用户不是同一人时才不允许添加
            if (StringHandlerUtil.compareStrIgnoreCaseWithOutEmpty("true", isExist) &&
                    !StringHandlerUtil.compareStrWithOutEmpty(userId, resultMap.get("userId"))) {
                return new SDKMessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(),"选择的房间下已有户主或管理员",requestId,responseTimestamp,"");
            }
            //查询当前项目信息
            ProjectPO projectPO = iOperateProjectServiceClient.getOneProject(projectId);
            //是否使用云对讲： 0-否，1-是
            Integer isSmartCommunity = projectPO.getIsSmartCommunity();

            String projectType = projectPO.getProjectType();
            //住宅最大授权数，最大为10
            Integer authMaxNum = projectPO.getAuthMaxNum();
            //办公最大授权数，最大为500
            Integer officeAuthMaxNum = projectPO.getOfficeAuthMaxNum();
            if (officeAuthMaxNum == 0) {
                officeAuthMaxNum = 11;
            }

            for (AppUserRoomDTO appUserRoomDTO : appUserRoomDTOS) {
                //当前房间中的住户数量
                Integer currentExistCount =
                        iPropertyHouseHoldInfoServiceClient.getMoveInHouseHoldCount(appUserRoomDTO.getRoomId(), projectId);

                Integer userExistCount = iPropertyHouseHoldInfoServiceClient.getUserMoveInHouseHoldCount(appUserRoomDTO.getRoomId(), projectId, userId);
                //获取该房屋类型 1住宅 2办公
                Integer housesType = iPropertyHouseHoldInfoServiceClient.getHousesType(appUserRoomDTO.getRoomId(), projectId);
                //当用户已在房间内时，不校验
                if (userExistCount > 0){
                    continue;
                }
                //已达到或超过项目中最大授权人数则无法添加住户
                if ("1".equals(projectType) && currentExistCount >= authMaxNum) {
                    return new SDKMessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(),String.format("%s房间中住户人数已达上限", appUserRoomDTO.getRoomNum()),requestId,responseTimestamp,"");
                }
                if ("2".equals(projectType) && currentExistCount >= officeAuthMaxNum) {
                    return new SDKMessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(),String.format("%s房间中住户人数已达上限", appUserRoomDTO.getRoomNum()),requestId,responseTimestamp,"");
                }
            }

            //查询用户的旧数据，便于判断用户名称及标签是否发生变化后是否向人脸识别系统推送数据
            Map<String, Object> oldUserInfo = iPropertyHouseHoldInfoServiceClient.getOldUserInfo(userId, projectId);
            boolean mark = false;
            if (oldUserInfo != null) {
                String userName = oldUserInfo.get("userName") == null ? "" : oldUserInfo.get("userName") + "";
                String userLable = oldUserInfo.get("userLabel") == null ? "" : oldUserInfo.get("userLabel") + "";
                String newUserLable = appUserGetUserInfoDTO.getUserLabel() == null ? "" : appUserGetUserInfoDTO.getUserLabel();
                String newUserName = appUserGetUserInfoDTO.getRealName() == null ? "" : appUserGetUserInfoDTO.getRealName();
                if (!userName.equals(newUserName) || !userLable.equals(newUserLable)) {
                    mark = true;
                }
            }
            iPropertyHouseHoldInfoServiceClient.updateAppUser(appUserGetUserInfoDTO, loginUserId, isSmartCommunity);

            //分配权限时若角色组不为空，则
            //找出用户原有的角色组
            this.userDeviceAuth(roleIdList, projectId, appUserGetUserInfoDTO.getUserId(), loginUserId);

            if (StringUtils.isNotBlank(appUserGetUserInfoDTO.getImageStr())) {//重新认证
                //判断项目是否开启人脸识别,并查询是否有百度库key
                OperateFaceApplyInfoVO operateFaceApplyInfoVO = iOperateFaceApplyServiceClient.getFaceByProjectId(appUserGetUserInfoDTO.getProjectId());
                if (operateFaceApplyInfoVO == null) {
                    return new SDKMessageVO(AppErrorCodeEnum.PROJECT_FACE_APPID_INEXISTENCE.getErrorCode(), requestId, responseTimestamp, "");
                }
                AppCreateBaiduFaceVO appCreateBaiduFaceVO = new AppCreateBaiduFaceVO();
                appCreateBaiduFaceVO.setAPP_ID(operateFaceApplyInfoVO.getAppId());
                appCreateBaiduFaceVO.setAPI_KEY(operateFaceApplyInfoVO.getApiKey());
                appCreateBaiduFaceVO.setSECRET_KEY(operateFaceApplyInfoVO.getSecretKey());
                appCreateBaiduFaceVO.setFaceScore(operateFaceApplyInfoVO.getFaceScore() == 0F ? 80F : operateFaceApplyInfoVO.getFaceScore());
                //判断图片分辨率
                BufferedImage bi = ImageIO.read(new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(appUserGetUserInfoDTO.getImageStr())));
                int width = bi.getWidth();
                int height = bi.getHeight();
                if (width < 640 || height < 480 || width > 2560 || height > 2560) {
                    return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_RESOLUTION_RATIO_ERROR.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
                }
                //保存图片
                String uploadFilePath = uploadImageFile(new BASE64Decoder().decodeBuffer(appUserGetUserInfoDTO.getImageStr()), "png", FileCatalogEnum.BAIDU_FACE_CREATE_FILE);
                appCreateBaiduFaceVO.setImageUrl(uploadFilePath);
                appCreateBaiduFaceVO.setUid(appUserGetUserInfoDTO.getUserId());

                //人脸判断
                SDKMessageVO messageVO = this.checkFace(appCreateBaiduFaceVO);
                if (messageVO != null) {
                    return messageVO;
                }
                //保存数据
                CloudFaceApiDTO dto = new CloudFaceApiDTO();
                dto.setUserId(appUserGetUserInfoDTO.getUserId());
                dto.setProjectId(projectId);
                dto.setRealName(appUserGetUserInfoDTO.getRealName());
                dto.setResponseTimestamp(responseTimestamp);
                dto.setPhoneNum(appUserGetUserInfoDTO.getPhoneNum());
                dto.setRequestId(requestId);
                messageVO = this.saveUserFace(dto.getUserId(), uploadFilePath, dto, appCreateBaiduFaceVO);
                if (messageVO != null) {
                    return messageVO;
                }
            }
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),request.getAttribute("requestId").toString(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(),request.getAttribute("requestId").toString(),responseTimestamp,
                            propertyUserInfoPO.getAppsecret()));
        } catch (Exception e) {
            throw new DataAccessException("【SDK基类_修改用户】修改用户失败",e);
        }
    }

    /**
     * <desc>
     * 保存人脸
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/11/05
     */
    private SDKMessageVO saveUserFace(String userId, String uploadFilePath, CloudFaceApiDTO dto, AppCreateBaiduFaceVO appCreateBaiduFaceVO) throws Exception {
        //保存数据
        AppUserProjectPO appUserProjectPO = new AppUserProjectPO();
        appUserProjectPO.setUserId(userId);
        appUserProjectPO.setProjectId(dto.getProjectId());
        appUserProjectPO.setFacePicUrl(uploadFilePath);
        appUserProjectPO.setFaceCreateTime(new Date());
        appUserProjectPO.setUpdateTime(new Date());
        appUserProjectPO.setIsFace(2);//认证中
        int updateNumber = iPropertyHouseHoldInfoServiceClient.updatePreUserBaiduFaceInfo(appUserProjectPO);
        if (updateNumber == 0) {
            return new SDKMessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
        }

        //添加人脸注册信息到队列
        appCreateBaiduFaceVO.setProjectId(dto.getProjectId());
        appCreateBaiduFaceVO.setUserPhone(dto.getPhoneNum());
        appCreateBaiduFaceVO.setUid(userId);
        appCreateBaiduFaceVO.setUserName(dto.getRealName());
        appCreateBaiduFaceVO.setUserInfo(dto.getRealName());//userInfo使用用户名
        appCreateBaiduFaceVO.setUploadFilePath(uploadFilePath);
        boolean resultCreateFace = iIotBaiduFaceServiceClient.createBaiduFace(appCreateBaiduFaceVO);
        if (!resultCreateFace) {
            return new SDKMessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
        }
        return null;
    }

    /**
     * <desc>
     * 人脸判断
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/11/05
     */
    private SDKMessageVO checkFace(AppCreateBaiduFaceVO appCreateBaiduFaceVO) {
        String checkResult = iIotBaiduFaceServiceClient.faceVerify(appCreateBaiduFaceVO);
        if (checkResult != null && !"".equals(checkResult)) {
            if ("error".equals(checkResult)) {//调用接口异常
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACEVERFY_ERROR.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("busy".equals(checkResult)) {//调用接口忙
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_BUSY.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("others".equals(checkResult)) {//图片不合格,非真人图片
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_PICTURE_ERROR.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("result_num".equals(checkResult)) {//人脸数异常
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_RESULTNUM_NOT_1.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("size".equals(checkResult)) {//人脸太小
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_SIZE_TOO_SMALL.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            //2020年8月5号 按照需求说明取消活体检测
           /* if ("faceliveness".equals(checkResult)) {//活体值异常
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_FACELIVENESS_TOO_LOW.getErrorCode(),appCreateBaiduFaceVO.getRequestId(),appCreateBaiduFaceVO.getResponseTimestamp(),"");
            }*/
            if ("left_eye".equals(checkResult) || "right_eye".equals(checkResult) || "nose".equals(checkResult)
                    || "mouth".equals(checkResult) || "left_cheek".equals(checkResult) || "right_cheek".equals(checkResult)
                    || "chin".equals(checkResult)) {//图片遮挡
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_OCCLUSION.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("blur".equals(checkResult)) {//模糊
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_BLUR_TOO_LOW.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("illumination_min".equals(checkResult)) {//光照过暗
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ILLUMINATION_TOO_LOW.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("illumination_max".equals(checkResult)) {//光照过亮
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ILLUMINATION_TOO_HIGH.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("pitch".equals(checkResult) || "roll".equals(checkResult) || "yaw".equals(checkResult)) {//角度
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ANGLE_NOT_STRAIGHT.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
            if ("completeness".equals(checkResult)) {//人脸完整度
                return new SDKMessageVO(PropertyErrorCodeEnum.APPUSER_FACE_COMPLETENESS_IMPERFECT.getErrorCode(), appCreateBaiduFaceVO.getRequestId(), appCreateBaiduFaceVO.getResponseTimestamp(), "");
            }
        }
        return null;
    }

    /**
     * <desc>
     * 上传图片文件
     * <desc/>
     *
     * @param bytes     图片二进制
     * @param imageType 图片类型
     * @return
     * @author Qiang.S
     * @createDate 2018-05-18
     */
    private String uploadImageFile(byte[] bytes, String imageType, FileCatalogEnum fileCatalog) {
        byte[] newbytes = ImgageUtil.stringToImage(bytes, imageType);
        ByteArrayInputStream byteArrayInputStream = null;
        if (newbytes != null) {
            byteArrayInputStream = new ByteArrayInputStream(newbytes);
        } else {
            byteArrayInputStream = new ByteArrayInputStream(bytes);
        }
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                byteArrayInputStream,
                imageType,
                FILE_ACCESS_URL,
                fileCatalog.getType()
        );

        try {
            //LOG.info("正在上传图片");
            Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
            //LOG.info("图片上传完毕");
            String returnCode = resultMap.get("returnCode").toString();
            if ("true".equals(returnCode)) {
                String fileUrl = resultMap.get("accessPath").toString();
                return fileUrl;
            } else {
                LOG.info(String.format("图片上传失败，returnCode: %s", returnCode));
                return null;
            }
        } catch (IOException e) {
            LOG.info("UploadFileUtil.uploadFile失败", e);
            return null;
        }
    }

    /**
     * <desc>
     *      分解前端传入的地址权限和分组权限,并返回分组权限
     * </desc>
     *
     * @param appUserRoomDTOS 地址信息列表 处理后赋值
     * @return roleIdList 角色组id列表
     * @Author Zhu.yj
     * @createDate  2021/4/19
     */
    private List<String> divideAddressAndRoleAuth( List<AppUserRoomDTO> appUserRoomDTOS, AppUserGetUserInfoDTO appUserGetUserInfoDTO) throws Exception{

        List<String> roleIdList = new ArrayList<>();
        List<AppUserRoomAndRoleInfoDTO> appUserRoomAndRoleInfoDTOS = JSONArray.parseArray(appUserGetUserInfoDTO.getAuthInfo(), AppUserRoomAndRoleInfoDTO.class);
        LOG.info(appUserGetUserInfoDTO.getAuthInfo());
        for (AppUserRoomAndRoleInfoDTO roomAndRoleInfoDTO : appUserRoomAndRoleInfoDTOS) {
            //房屋授权
            if ("1".equals(roomAndRoleInfoDTO.getAuthType())) {
                AppUserRoomDTO userRoomDTO = new AppUserRoomDTO();
                List<String> singleAddress = roomAndRoleInfoDTO.getAddressList();
                //由于云对讲SDK对外 需要传入buildNum unitNum等，故在此需转换为buildId unitId等
                userRoomDTO.setBuildNum(singleAddress.get(0));
                userRoomDTO.setUnitNum(singleAddress.get(1));
                userRoomDTO.setRoomNum(singleAddress.get(2));
                userRoomDTO.setProjectId(appUserGetUserInfoDTO.getProjectId());
                AppUserRoomDTO roomInfo = iPropertyHouseHoldInfoServiceClient.getRoomInfo(userRoomDTO);
                if(roomInfo==null){
                    List<String> msgList = new ArrayList<>();
                    msgList.add("楼栋编号:"+singleAddress.get(0)+",单元编号:"+singleAddress.get(1)+",房间编号:"+singleAddress.get(2)+"信息有误，请检查");
                    return msgList;
                }
                userRoomDTO.setBuildId(roomInfo.getBuildId());
                userRoomDTO.setUnitId(roomInfo.getUnitId());
                userRoomDTO.setRoomId(roomInfo.getRoomId());

                //目前若要沿用之前的逻辑的话需要传入roomNum，但需求变更之后前端无法传入roomNum
                String roomNum = iPropertyHouseHoldInfoServiceClient.getRoomNum(userRoomDTO.getRoomId());
                userRoomDTO.setRoomNum(roomNum);
                userRoomDTO.setHouserType(Integer.valueOf(roomAndRoleInfoDTO.getHouseType()));
                appUserRoomDTOS.add(userRoomDTO);
            }
            if ("2".equals(roomAndRoleInfoDTO.getAuthType())){
                roleIdList = roomAndRoleInfoDTO.getRoleIdList();
            }
        }
        return roleIdList;
    }

    /**
     * <desc>
     * 判断添加住户业主房间地址时房间是否已存在业主
     * <desc/>
     *
     * @param appUserRoomDTOS App用户房间信息传输数据集
     * @return Map<String, String> :
     * Map<String, value> isExist业主是否存在，roomNum 业主存在时的房间号,userId 业主userId
     * @author zhangs
     * @createDate 2017/09/20
     */
    private Map<String, String> checkOwnerExist(List<AppUserRoomDTO> appUserRoomDTOS) {
        Map<String, String> resultMap = new HashMap<>();
        if (appUserRoomDTOS == null || (appUserRoomDTOS.isEmpty())) {
            resultMap.put("isExist", "false");
            return resultMap;
        }
        for (AppUserRoomDTO appUserRoomDTO : appUserRoomDTOS) {
            if (appUserRoomDTO.getHouserType() == AppUserRoomHouserTypeEnum.USERROOM_HOUSERTYPE_OWNER.getType()) {
                AppUserRoomOwnerIsExistDTO appUserRoomOwnerIsExistDTO = new AppUserRoomOwnerIsExistDTO();
                appUserRoomOwnerIsExistDTO.setRoomId(appUserRoomDTO.getRoomId());
                //获取roomId对应房间是否已存在业主
                List<AppUserRoomPO> appUserRoomPOS =
                        iPropertyHouseHoldInfoServiceClient.getExistHouserByRoom(appUserRoomOwnerIsExistDTO);
                if (appUserRoomPOS != null && appUserRoomPOS.size() > 0) {
                    resultMap.put("isExist", "true");
                    resultMap.put("roomNum", appUserRoomDTO.getRoomNum());
                    resultMap.put("userId", appUserRoomPOS.get(0).getUserId());
                    break;
                }
            }
        }
        return resultMap;
    }

    /**
     * <desc>
     *      用户角色组设备授权
     * </desc>
     *
     * @param roleIdList 用户角色组id列表
     * @param projectId 项目id
     * @param userId 用户id
     * @param loginUserId 操作人id
     * @return
     * @Author Zhu.yj
     * @createDate  2021/4/12
     */
    private void userDeviceAuth(List<String> roleIdList, String projectId, String userId, String loginUserId) throws Exception{
        List<Map<String,Object>> list = new ArrayList<>();
        //获取用户的临时权限数据
        Map<String, Object> tempAuthMap = iPropertyHouseHoldInfoServiceClient.getOldUserTempAuth(userId,projectId);
        list.add(tempAuthMap);

        //用户角色组授权
        PropertyHouseholdRoleAuthDTO propertyHouseholdRoleAuthDTO = new PropertyHouseholdRoleAuthDTO();
        propertyHouseholdRoleAuthDTO.setRoleId(String.join(",", roleIdList));
        propertyHouseholdRoleAuthDTO.setProjectId(projectId);
        propertyHouseholdRoleAuthDTO.setUserIds(userId);
        iPropertyHouseholdRoleServiceClient.userRoleGroupAuth(propertyHouseholdRoleAuthDTO);

        //门禁授权
        String currentDevices = iPropertyHouseholdRoleServiceClient.getAllDeviceUniqueStr(projectId);
        if (StringUtils.isBlank(currentDevices)) {
            currentDevices = "";
        }
        String deviceUniqueStrByRoleId = "";
        if(!roleIdList.isEmpty()){
            //找出当前选择的角色分组的所有门禁设备
            List<String> deviceUniqueListByRoleId = iPropertyHouseholdRoleServiceClient.getDeviceUniqueListByRoleId(String.join(",", roleIdList),"1");
            deviceUniqueStrByRoleId = deviceUniqueListByRoleId.toString().replace("[", "").replace("]", "").replaceAll(" ","");
        }
        iPropertyDeviceAuthServiceClient.updateHouseHoldTmpDeviceAuth(loginUserId, userId, projectId, 2
                , currentDevices, deviceUniqueStrByRoleId, new ArrayList<>(), "mark");



        //处理用户电梯设备权限表信息
        String deviceUniqueStrElevatorByRoleId = "";
        List<String> floorArr = new ArrayList<>();
        if (!roleIdList.isEmpty()){
            Map<String,Object> map = iPropertyHouseholdRoleServiceClient.getElevatorListByRoleId(String.join(",", roleIdList),"1");
            String allElevatorDevices = iPropertyHouseholdRoleServiceClient.getAllElevatorDeviceUniqueStr(projectId);
            if (StringUtils.isBlank(allElevatorDevices)) {
                allElevatorDevices = "";
            }
            if (map != null){
                List<String> deviceUniqueByElevatorArr = (List<String>) map.get("deviceUniqueArr");
                floorArr =(List<String>) map.get("floorArr");
                if (deviceUniqueByElevatorArr != null && !deviceUniqueByElevatorArr.isEmpty()){
                    deviceUniqueStrElevatorByRoleId = String.join(",", deviceUniqueByElevatorArr);
                }
            }
            if (floorArr == null){
                floorArr = new ArrayList<>();
            }
            iPropertyDeviceAuthServiceClient.updateHouseHoldTmpDeviceAuth(loginUserId, userId, projectId, 1
                    , allElevatorDevices, deviceUniqueStrElevatorByRoleId, floorArr, "mark");
        }else {
            //当角色组为空时，删除了用户所有的角色分组，此时删掉用户的分组设备权限
            iPropertyDeviceAuthServiceClient.deleteUserDeviceAuth(projectId, userId);
        }


        for(Map<String,Object> tempAuth : list) {
            //推送云门禁 云電梯分組权限数据
            iPropertyHouseHoldInfoServiceClient.pushTempUserInfos(projectId, tempAuth.get("userId").toString(), StringHandlerUtil.getNullOrStringForObject(tempAuth.get("doorAuth")),
                    StringHandlerUtil.getNullOrStringForObject(tempAuth.get("elevatorAuth")), StringHandlerUtil.getNullOrStringForObject(tempAuth.get("talkAuth")),"");
        }

    }
}

